//
//  HomeViewController.m
//  HAODE
//
//  Created by LiYinDi on 15/12/22.
//  Copyright © 2015年 reabam.com. All rights reserved.
//

#import "P004HomeViewController.h"
#import "P004JKSideSlipView.h"
#import "P004MenuView.h"
#import "MessageViewController.h"
#import "RDVTabBarController.h"
#import "TheLoginViewController.h"
#import "UIImage+RTTint.h"
#import "PlaceOrderViewController.h"
#import "GenerateQRCodeViewController.h"
#import "UIButton+UIButtonImageAndText.h"
#import "HttpRequest.h"
#import "ActivityViewController.h"
//#import "PlaceOrderViewController.h"
 

@interface P004HomeViewController ()<P004JKSideSlipViewDelegate,P004MenuViewDelegate>
{
    P004JKSideSlipView *_sideSlipView;
    NSArray *textArray;
    NSArray *imageArray;
    NSArray *colorArray;
    NSMutableArray *selectedTextArray;
    NSMutableArray *selectedImageArray;
    NSArray *defaultTextArray;
    NSArray *defaultImageArray;

    NSArray *viewControllerArray;
    BOOL isDefault;
    BOOL sliderIsOpen;
}
@end

@implementation P004HomeViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.title = @"经营";
    }
    return self;
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:YES];
    // self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
    
}

-(void)viewWillAppear:(BOOL)animated
{
    NSLog(@"rrtyyiyiyiu");
    self.navigationController.navigationBarHidden=YES;
     [[self rdv_tabBarController] setTabBarHidden:NO];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* tokenId = [user objectForKey:@"tokenId"];
    if (tokenId.length==0) {
        TheLoginViewController* Login=[[TheLoginViewController alloc]init];
        [self.navigationController pushViewController:Login animated:YES];
    }
   [self requestUnreadMessageCount];
   
}
-(void)requestUnreadMessageCount
{
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    
    //    [Global showIndeterminateHud:@"加载中，请稍后。。。" delay:30 view:self.view];
    [HttpRequest requestData:@"MsgCenter/NReadCount" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        //  NSLog(@"sssss===%@",severDataDict.dataDict);
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                NSString *hasNRead=[severDataDict.dataDict objectForKey:@"hasNRead"];
                if ([hasNRead isEqualToString:@"Y"]) {
                    _dotLabel.hidden=NO;
                }
                else
                {
                    _dotLabel.hidden=YES;
                }
                
            }else{
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                //  [Global showTextHud:requestResultStr view:self.view];
                [Global showTextHudSub:requestResultStr view:self.view];
                
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    TheLoginViewController *loginVC=[[TheLoginViewController alloc] init];//2.0{9个参数 少2个}
                    [self.navigationController pushViewController:loginVC animated:YES];
                }
                

                
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSLog(@"rrtyyiyiyiu");
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 93)];
    [view setBackgroundColor:[UIColor clearColor]];
    UIVisualEffect *blurEffect;
    blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight];
    
    UIVisualEffectView *frostedView;
    frostedView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    
    frostedView.frame = view.bounds;
    [view addSubview:frostedView];
    [_contentView addSubview:view];
    [_contentView bringSubviewToFront:_topView];
    [_topView setBackgroundColor:[UIColor clearColor]];
    self.automaticallyAdjustsScrollViewInsets=NO;
    // Do any additional setup after loading the view from its nib.
    _dotLabel.layer.cornerRadius=4;
    _dotLabel.layer.masksToBounds=YES;
    isDefault=YES;
    sliderIsOpen=NO;
    _sideSlipView = [[P004JKSideSlipView alloc]initWithSender:self];
    _sideSlipView.delegate=self;
    _sideSlipView.backgroundColor = [UIColor whiteColor];
    P004MenuView *menu = [P004MenuView menuView];
    menu.delegate=self;
    [menu didSelectRowAtIndexPath:^(id cell, NSIndexPath *indexPath) {
    [_sideSlipView hide];
        
    }];
    [_leftSliderBtn setImage:[UIImage imageNamed:@"jingying_new.png"] forState:UIControlStateNormal];
      viewControllerArray=[NSArray arrayWithObjects:@"MemberListViewController",@"CouponListViewController",@"GenerateQRCodeViewController",@"OrderListViewController",  @"DeliverylistViewController",  @"NeedOrderListViewController",@"WhsInListViewController",@"WhsOutListViewController",  nil];
    
    menu.items = @[@{@"title":@"营销管理" },@{@"title":@"销售管理" },@{@"title":@"库存管理"}];
    
    [_sideSlipView setContentView:menu];
    [self.view addSubview:_sideSlipView];
    
    selectedTextArray=[NSMutableArray array];
    selectedImageArray=[NSMutableArray array];
    defaultTextArray=[NSArray arrayWithObjects:@"会员", @"我的店铺",@"销售订单",@"受理配送",@"要货管理",@"商品入库",@"商品出库",nil];
    defaultImageArray=[NSArray arrayWithObjects: @"huiyuan",
                       
                       @"dianpuerweima",
                       @"xiaoshoudingdan",
                       @"tihuopeisong",
                       @"yaohuoguanli",
                       @"shangpinruku",
                       @"shangpinchuku", nil];
    
    textArray=[NSArray arrayWithObjects:@"会员", @"优惠券",@"我的店铺",@"销售订单",@"受理配送",@"要货管理",@"商品入库",@"商品出库",nil];
    imageArray=[NSArray arrayWithObjects: @"huiyuan", @"youhuiquan",
                
                @"dianpuerweima",
                @"xiaoshoudingdan",
                @"tihuopeisong",
                @"yaohuoguanli",
                @"shangpinruku",
                @"shangpinchuku", nil];
    colorArray =[NSArray arrayWithObjects:[UIColor colorWithRed:31.00/255.0 green:65.00/255.0 blue:99.00/255.0 alpha:1],[UIColor colorWithRed:31.00/255.0 green:62.00/255.0 blue:107.00/255.0 alpha:1], [UIColor colorWithRed:31.00/255.0 green:92.00/255.0 blue:121.00/255.0 alpha:1],[UIColor colorWithRed:31.00/255.0 green:103.00/255.0 blue:86.00/255.0 alpha:1],[UIColor colorWithRed:64.00/255.0 green:95.00/255.0 blue:31.00/255.0 alpha:1],[UIColor colorWithRed:102.00/255.0 green:98.00/255.0 blue:31.00/255.0 alpha:1],[UIColor colorWithRed:100.00/255.0 green:31.00/255.0 blue:46.00/255.0 alpha:1],[UIColor colorWithRed:105.00/255.0 green:46.00/255.0 blue:31.00/255.0 alpha:1],nil];
    
    [self setAutolayOut];
    [self setUserSelectedDefault];
    
    
}
-(void)setUserSelectedDefault
{
    
    [selectedTextArray removeAllObjects];
    [selectedImageArray removeAllObjects];
    for (UIView *v in _scrollView.subviews) {
        [v removeFromSuperview];
    }
    int selectedID=0;
    int m=0;
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    for ( int i=0; i<4; i++) {
        NSString *parentKeyStr= [NSString stringWithFormat:@"parent%ld",(long)i];
        if ([userDefaults dictionaryForKey:parentKeyStr]) {
            isDefault=NO;
        }
        NSMutableDictionary *dict=[NSMutableDictionary  dictionaryWithDictionary:[userDefaults dictionaryForKey:parentKeyStr]];
        // NSLog(@"dict===%@",dict);
        NSMutableArray *array=[NSMutableArray arrayWithArray:[dict objectForKey:@"addOrSubtractARRAY"]];
        
        for (int j=0; j<array.count; j++) {
            
            if ([[array objectAtIndex:j]isEqualToString:@"Y"]) {
                
                selectedID=m;
                [selectedTextArray addObject:[textArray objectAtIndex:selectedID]];
                [selectedImageArray addObject:[imageArray objectAtIndex:selectedID]];
            }
            m++;
        }
    }
    if (isDefault) {
        for (int i=0; i<defaultImageArray.count; i++) {
            [selectedTextArray addObject:[defaultTextArray objectAtIndex:i ]];
            [selectedImageArray addObject:[defaultImageArray objectAtIndex:i]];
        }
        
    }
    
    if (selectedTextArray.count==0)
    {
        
        UIButton *addButton=[UIButton buttonWithType:UIButtonTypeCustom];
        
        addButton.frame=CGRectMake(10, 93, ((ScreenWidth-25)/2), (ScreenHeight-187)/4);
        
        
        addButton.backgroundColor=[UIColor colorWithRed:240.0f/255.0f green:240.0f/255.0f blue:240.0f/255.0f alpha:1.0f];
        [addButton setImage:[UIImage imageNamed:@"datianjia_new.png"] withTitle:@"添加" forState:UIControlStateNormal];
        [addButton setTitleColor:[UIColor colorWithRed: 204.0/255.0f green:204.0/255.0f blue:204.0/255.0f alpha:1.0] forState:UIControlStateNormal];
        
        [addButton addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
        
        [_scrollView addSubview:addButton];
        
        [_scrollView setContentSize:CGSizeMake(0, addButton.frame.origin.y+ addButton.frame.size.height)];
        
        [_scrollView setScrollEnabled:YES];
        
    }
    
    else
    {
        for (int i=0; i<selectedTextArray.count; i++) {
            UIButton *selectedButton=[UIButton buttonWithType:UIButtonTypeCustom];
            selectedButton.frame=CGRectMake(10+(i%2)*((ScreenWidth-25)/2+5),93+ 5*(i/2)+(i/2)*(ScreenHeight-187)/4, ((ScreenWidth-25)/2), (ScreenHeight-187)/4);
            //        NSLog(@"(ScreenHeight-15-79-78)/4===%f",ScreenHeight);
            selectedButton.backgroundColor=colorArray[i%8];
            selectedButton.tag=i;
            // NSLog(@"width===%0.02f",selectedButton.frame.size.width);
            [selectedButton addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
            [selectedButton setImage:[UIImage imageNamed:[selectedImageArray objectAtIndex:i]] withTitle:[selectedTextArray objectAtIndex:i] forState:UIControlStateNormal];
            
            
            [_scrollView addSubview:selectedButton];
            if (i==selectedTextArray.count-1) {
                UIButton *addButton=[UIButton buttonWithType:UIButtonTypeCustom];
                
                addButton.frame=CGRectMake(10+(selectedTextArray.count%2)*((ScreenWidth-25)/2+5), 93+5*(selectedTextArray.count/2)+(selectedTextArray.count/2)*(ScreenHeight-187)/4, ((ScreenWidth-25)/2), (ScreenHeight-187)/4);
                
                
                addButton.backgroundColor=[UIColor colorWithRed:240.0f/255.0f green:240.0f/255.0f blue:240.0f/255.0f alpha:1.0f];
                [addButton setImage:[UIImage imageNamed:@"datianjia_new.png"] withTitle:@"添加" forState:UIControlStateNormal];
                [addButton setTitleColor:[UIColor colorWithRed: 204.0/255.0f green:204.0/255.0f blue:204.0/255.0f alpha:1.0] forState:UIControlStateNormal];
                [addButton addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
                
                [_scrollView addSubview:addButton];
                
                [_scrollView setContentSize:CGSizeMake(0, addButton.frame.origin.y+ addButton.frame.size.height +49)];
                
                [_scrollView setScrollEnabled:YES];
                
            }
            
            
        }
    }
    
}
-(void)btnClick:(UIButton *)sender
{
    if (sliderIsOpen) {
        [_sideSlipView hide];
        sliderIsOpen=NO;
    }
    else
    {
        if (selectedTextArray.count>sender.tag) {
            //        sliderIsOpen=NO;
            //        [_sideSlipView hide];
            //[[self rdv_tabBarController] setTabBarHidden:YES];
            NSString *str=[selectedTextArray objectAtIndex:sender.tag];
            
            NSInteger index=[textArray indexOfObject:str];
            
            NSString *vcStr=[viewControllerArray objectAtIndex:index];
            if ([vcStr isEqualToString:@"ActivityViewController"]) {
                [Global setType:@"Act"];
            }
            else if ([vcStr isEqualToString:@"PlaceOrderViewController"]) {
                [Global setType:@"PlaceOrder"];
                [Global setPlaceOrderPType:@"saleItem"];
                
            }
            else if ([vcStr isEqualToString:@"GenerateQRCodeViewController"])
            {
                [Global setType:@"GetCompanyQrCode"];
                
            }
            
                    UIViewController * vc = (UIViewController*)[[NSClassFromString(vcStr) alloc] init];
                    
                    if (vc==nil) {
                        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"尚未开通" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                        [alert show];
                    }
                    else
                    {
                        [self.navigationController pushViewController:vc animated:YES];
                    }
           
        }
    }
}

-(void)subTableviwAddOrSubtractClickAtHome
{
    
    [self setUserSelectedDefault];
}
- (void) didSelectCellAtChildIndex:(NSInteger)childIndex withInParentCellIndex:(NSInteger)parentIndex
{
    
    NSArray *vcArray = [[NSArray alloc] initWithObjects:
                        [NSArray arrayWithObjects:@"MemberListViewController",@"CouponListViewController",@"GenerateQRCodeViewController",nil],
                        [NSArray arrayWithObjects:@"OrderListViewController",  @"DeliverylistViewController",nil],
                        //[NSArray arrayWithObjects:@"GetProductListViewController",@"BusinessWhsInListViewController",@"WhsOutListViewController", nil],
                        [NSArray arrayWithObjects:@"NeedOrderListViewController",@"WhsInListViewController",@"WhsOutListViewController",nil],
                        
                        nil];

    NSString *vcStr=[[vcArray objectAtIndex:parentIndex] objectAtIndex:childIndex];
    
    if ([vcStr isEqualToString:@"ActivityViewController"]) {
        [Global setType:@"Act"];
    }
    else if ([vcStr isEqualToString:@"PlaceOrderViewController"]) {
        [Global setType:@"PlaceOrder"];
        [Global setPlaceOrderPType:@"saleItem"];
    }
    else if ([vcStr isEqualToString:@"GenerateQRCodeViewController"])
    {
        [Global setType:@"GetCompanyQrCode"];
    }
    
            UIViewController * vc = (UIViewController*)[[NSClassFromString(vcStr) alloc] init];
            
            
            if (vc==nil) {
                UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"尚未开通" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
            }
            else
            {
                [_sideSlipView hide];
                sliderIsOpen=NO;
                [self.navigationController pushViewController:vc animated:YES];
            }
    
}
-(void)hideSlider
{
    [[self rdv_tabBarController] setTabBarHidden:NO];
    _homeBtnView.hidden=YES;
    [_topView setBackgroundColor:[UIColor clearColor]];
    //    [[[self rdv_tabBarController] tabBar] setFrame:CGRectMake(0, ScreenHeight-49, ScreenWidth, 49)];
    //    [[[self rdv_tabBarController] blurView] setFrame:CGRectMake(0, ScreenHeight-49, ScreenWidth, 49)];
    [UIView animateWithDuration:0.3 animations:^{
        [_contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left) ;
            make.width.equalTo(self.view.mas_width);
            make.bottom.equalTo(self.view.mas_bottom) ;
            make.top.equalTo(self.view.mas_top) ;
        }];
    } completion:^(BOOL finished) {
        
    }];
    
    
    sliderIsOpen=NO;
    
    
}
-(void)showSlider
{
    
    [_scrollView setContentOffset:CGPointMake(0, 0)];
    sliderIsOpen=YES;
    
    [[self rdv_tabBarController] setTabBarHidden:YES];
    _homeBtnView.hidden=YES;
    [_topView setBackgroundColor:[UIColor clearColor]];
    
    [_contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).with.offset(250);
        make.width.equalTo(self.view.mas_width);
        
        make.bottom.equalTo(self.view.mas_bottom) ;
        
        
        make.top.equalTo(self.view.mas_top) ;
    }];
    
    
}
-(void)menuViewHomeBtnClick
{
    sliderIsOpen=NO;
    [_sideSlipView hide];
}
-(void)menuViewConfirmCancelClick
{
    [_sideSlipView hide];
    TheLoginViewController* Login=[[TheLoginViewController alloc]init];
    
    [self.navigationController pushViewController:Login animated:YES];
    
}
- (IBAction)leftSliderBtnClick:(id)sender {
    
    if (sliderIsOpen) {
        [[self rdv_tabBarController] setTabBarHidden:NO];
        _homeBtnView.hidden=YES;
        [_topView setBackgroundColor:[UIColor clearColor]];
        [_sideSlipView hide];
        sliderIsOpen=NO;
        
        
    }
    else
    {
        [[self rdv_tabBarController] setTabBarHidden:YES];
        _homeBtnView.hidden=NO;
        [_scrollView setContentOffset:CGPointMake(0, 0)];
        [_topView setBackgroundColor:[UIColor whiteColor]];
        [_sideSlipView show];
        sliderIsOpen=YES;
        
    }
    // sliderIsOpen=!sliderIsOpen;
}
- (void)addBtnClick{
    if (sliderIsOpen) {
        [[self rdv_tabBarController] setTabBarHidden:NO];
        _homeBtnView.hidden=YES;
        [_topView setBackgroundColor:[UIColor clearColor]];
        [_sideSlipView hide];
        sliderIsOpen=NO;
        
    }
    else
    {
        
        [[self rdv_tabBarController] setTabBarHidden:YES];
        _homeBtnView.hidden=NO;
        [_scrollView setContentOffset:CGPointMake(0, 0)];
        [_topView setBackgroundColor:[UIColor whiteColor]];
        [_sideSlipView show];
        sliderIsOpen=YES;
        
    }
    
}

- (IBAction)messageBtnClick:(id)sender {
    MessageViewController *messageVC = [[MessageViewController alloc] init];
    
    [self.navigationController pushViewController:messageVC animated:YES];
}

-(void)setAutolayOut
{
    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.width.equalTo(self.view.mas_width);
        
        //        make.bottom.equalTo(self.view.mas_bottom).with.offset(-[[[self rdv_tabBarController] tabBar] height]) ;
        
        make.bottom.equalTo(self.view.mas_bottom);
        make.top.equalTo(self.view.mas_top) ;
    }];
    
    [_homeBtnView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        
        make.bottom.equalTo(self.view.mas_bottom);
        // make.height.equalTo(_memberButton.mas_width).with.multipliedBy(_memberButton.height/_memberButton.width);
        make.height.equalTo(@49);
        make.width.equalTo(_contentView.mas_width);
        
    }];
    
    [_homeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_homeBtnView.mas_left).with.offset(10) ;
        
        make.bottom.equalTo(_homeBtnView.mas_bottom);
        // make.height.equalTo(_memberButton.mas_width).with.multipliedBy(_memberButton.height/_memberButton.width);
        make.height.equalTo(@49);
        make.width.equalTo(_contentView.mas_width).dividedBy(5);
        
    }];
    [_zhanTingBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_homeBtn.mas_right)  ;
        
        make.bottom.equalTo(_homeBtnView.mas_bottom);
        // make.height.equalTo(_memberButton.mas_width).with.multipliedBy(_memberButton.height/_memberButton.width);
        make.height.equalTo(@49);
        make.width.equalTo(_contentView.mas_width).dividedBy(5);
        
    }];
    
    [_topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_contentView.mas_left);
        make.width.equalTo(_contentView.mas_width);
        
        make.height.equalTo(@93);
        make.top.equalTo(_contentView.mas_top) ;
    }];
    
    [_leftSliderBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_contentView.mas_left).with.offset(5);
        
        make.top.equalTo(_contentView.mas_top).with.offset(41.5);
        // make.height.equalTo(_memberButton.mas_width).with.multipliedBy(_memberButton.height/_memberButton.width);
        make.height.equalTo(@30);
        make.width.equalTo(@40);
        
    }];
    
    [_messageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        // make.left.equalTo(_scanBtn.mas_right).with.offset(10);
        make.right.equalTo(_contentView.mas_right).with.offset(-10);
        make.top.equalTo(_contentView.mas_top).with.offset(41.5);
        // make.height.equalTo(_memberButton.mas_width).with.multipliedBy(_memberButton.height/_memberButton.width);
        make.height.equalTo(@30);
        make.width.equalTo(@40);
        
    }];
    [_dotLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(_contentView.mas_right).with.offset(-12);
        make.top.equalTo(_contentView.mas_top).with.offset(45.5);
        // make.height.equalTo(_memberButton.mas_width).with.multipliedBy(_memberButton.height/_memberButton.width);
        make.height.equalTo(@8);
        make.width.equalTo(@8);
        
    }];
    
    [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_contentView.mas_left);
        make.width.equalTo(_contentView.mas_width);
        make.top.equalTo(_contentView.mas_top)  ;
        make.bottom.equalTo(_contentView.mas_bottom);
    }];
    
}
 @end
